#!/usr/bin/env drgn
from drgn import Program
from drgn import container_of
from drgn.helpers.linux.pid import find_task
from drgn.helpers.linux.cpumask import for_each_possible_cpu
from drgn.helpers.linux.percpu import per_cpu, per_cpu_ptr

import sys
import time

def get_cpuacct_task(task):

    css = task.cgroups.subsys[prog['cpuacct_cgrp_id']]
    css_ca = container_of(css, 'struct cpuacct', 'css')

    return css_ca


def work():
    pid = sys.argv[1]
    task = find_task(prog, int(pid))

    cpuacct = get_cpuacct_task(task)

    #for cpu in for_each_possible_cpu():
    cpustat = per_cpu_ptr(cpuacct.cpustat, 128).cpustat

    sys_old = 0
    syscpu = 0
    ts = time.time()
    ts_old = ts
    while True:
        ts = time.time()
        syscpu = cpustat[prog['CPUTIME_SYSTEM']].value_()
        irq = cpustat[prog['CPUTIME_IRQ']].value_()
        sirq = cpustat[prog['CPUTIME_SOFTIRQ']].value_()
        print(f'sys: {syscpu} irq: {irq} softirq {sirq}')
        es = ts - ts_old
        scpu = syscpu - sys_old
        usage = (scpu / es) / 1000000000 * 100 / 2
        print(f'sys usage: {usage:.2f} %')
        sys_old = syscpu
        ts_old = ts
        time.sleep(1)


if __name__ == '__main__':
    work()
